package com.ruoyi.web.controller.shopping.user;

import com.ruoyi.system.domain.User;
import com.ruoyi.system.service.UserService;
import com.ruoyi.system.view.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/xiaomi/v2/ms/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R<String> login(@RequestBody User user){
        String s = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(s);
        boolean b = userService.checkLogin(user);
        if (b == true){
            User info = userService.info(Integer.valueOf(userService.getIdByUsername(user.getUsername())));
            if (info.getState() == 0){
                System.out.println("登录成功");
                String idByUsername = userService.getIdByUsername(user.getUsername());
                return R.success(idByUsername);
            }
            return R.error("该用户已经被禁用");
        }else {
            System.out.println("登录失败");
        }
        return R.error("账号或密码错误");
    }

    @PostMapping("/register")
    public R<String> registerUser(@RequestBody User user){
        //密码进行加密
        String s = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(s);
        userService.registerUser(user);
        return R.success("注册成功。");
    }

    @GetMapping("/info/{id}")
    public R<User> info(@PathVariable(value = "id") Integer id){
        User user = userService.info(id);
        if (user == null){
            return R.error("没有找到用户信息。");
        }
        return R.success(user);
    }

}
